package net.topicopedia.servlets.categories;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class GetTagsForCategoryServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		Key key = KeyFactory.createKey("Category", Long.parseLong(req.getParameter("category") ) );
		
		resp.addHeader("Access-Control-Allow-Origin", "*");
		resp.setContentType("text/plain");
		
		String output = "";
		
		Entity category = null;
		
		try {
			category = datastore.get(key);
		} catch (EntityNotFoundException e) {
			e.printStackTrace();
		} finally 
		{
			if ( category != null )
			{
				String storedUuid = category.getKey().getId() + "";
				String storedName = (String) category.getProperty("name");
				String storedTagsString = ( (Text) category.getProperty("tags") ).getValue();
				JSONObject jsonTags = null;
				try {
					jsonTags = new JSONObject( storedTagsString );
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				JSONArray jsonTag = null;
				try {
					jsonTag = (JSONArray) jsonTags.get("tags");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String storedCount = (Long) category.getProperty("count") + "";
			  
				output += "{ \"uuid\": \"" + storedUuid + "\", \"name\": \"" + storedName + "\", \"tags\":" + jsonTag.toString() + ", \"count\": \"" + storedCount + "\"}";
			}
		}

		
		resp.getWriter().println( output );
		
	}
}
 